<script setup lang="ts">
import { useScriptTag } from '@vueuse/core'
import { onMounted, onUnmounted } from 'vue'

const { params } = defineProps<{
  params: Record<string, string>
}>()
const emits = defineEmits<{
  callback: [code: string]
}>()

const { load, unload } = useScriptTag('https://g.alicdn.com/dingding/h5-dingtalk-login/0.21.0/ddlogin.js', () => {
  window.DTFrameLogin(
    {
      id: 'self_defined_element',
    },
    {
      redirect_uri: encodeURIComponent(params.redirect_uri),
      client_id: params.client_id,
      scope: params.scope,
      response_type: 'code',
      state: params.state,
      prompt: 'consent',
    },
    async (loginResult) => {
      const { authCode } = loginResult
      emits('callback', authCode)
    },
    (errorMsg) => {
      // 这里一般需要展示登录失败的具体原因,可以使用toast等轻提示
      console.error(`errorMsg of errorCbk: ${errorMsg}`)
    },
  )
}, { manual: true })

onMounted(load)
onUnmounted(unload)
</script>

<template>
  <div id="self_defined_element" class="flex items-center justify-center" />
  <div class="py-2 text-center text-sm font-semibold">
    请使用钉钉APP扫码
  </div>
</template>
